import pymysql
import urllib.request
import json

db = pymysql.connect("114.115.160.16", "root", "123456Aa!", "fund")
cursor = db.cursor()

headers = {
    "token": "atTPd9c8sA"
}
req = urllib.request.Request(url="https://api.doctorxiong.club/v1/fund/all", headers=headers)
response = urllib.request.urlopen(req)
all_fund = json.loads(response.read().decode("UTF-8"))
idid = 1

number_of_fund = 1000

for fund in all_fund["data"][0:number_of_fund]:
    fund_id = fund[0]  # 基金代码
    fund_name = fund[2]  # 基金名称
    category = fund[3]  # 基金类型
    if category == "股票型":
        category = 1
    elif category == "混合型":
        category = 2
    elif category == "债券型":
        category = 3
    elif category == "指数型":
        category = 4
    elif category == "货币型":
        category = 5

    if category != 5:
        continue

    try:
        response = urllib.request.urlopen("https://api.doctorxiong.club/v1/fund/detail" + "?code=" + fund[
            0] + "&startDate=2021-05-12" + "&token=atTPd9c8sA").read().decode("UTF-8")
        fund_info = eval(response)["data"]
        if fund_info["buyMin"] == "":
            buy_min = 0
        else:
            buy_min = float(fund_info["buyMin"])
        manager = fund_info["manager"]
        buy_source_rate = float(fund_info["buySourceRate"])
        buy_rate = float(fund_info["buyRate"])
        #day_growth = float(fund_info["dayGrowth"])
        #week_growth = float(fund_info["lastWeekGrowth"])
        day_growth = 0
        week_growth = 0
        if fund_info["lastMonthGrowth"] == "":
            month_growth = 0
        else:
            month_growth = float(fund_info["lastMonthGrowth"])
        if fund_info["lastYearGrowth"] == "":
            year_growth = 0
        else:
            year_growth = float(fund_info["lastYearGrowth"])
        sql = "insert into api_fund values('%s','%s',%d,%f,'%s',%f,%f,%f,%f,%f,0,0,%f)" % (
        fund_id, fund_name, category, buy_min, manager, buy_source_rate, buy_rate, day_growth, week_growth,
        month_growth, year_growth)
        #print(sql)
        cursor.execute(sql)
        print("ok!!", fund_id)
    except Exception as e:
        print(e, fund_info)
        # print("fail!!", fund_info)
db.commit()
